package com.kaifamiao.jdbc.d0908;

import java.sql.*;
import java.util.List;

public class DBUtil {

    static {
        loadDriver();
    }

    private static void loadDriver(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private String url;
    private String user;
    private String password;

    private Connection conn;

    public DBUtil(String url, String user, String password){
        this.url = url;
        this.user = user;
        this.password = password;
    }

    public Connection getConnection(){
        if (conn == null){
            conn = getConnection(this.url, this.user, this.password);
        }
        return conn;
    }

    public static Connection getConnection(String url, String user, String password){
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static PreparedStatement before(Connection connection, String sql, Object...params){
        try(
                PreparedStatement statement = connection.prepareStatement(sql);
        ) {
            for (int i = 0; i < params.length; i++) {
                statement.setObject(i + 1, params[i]);
            }
            return statement;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int update(Connection connection, String sql, Object...params){
        PreparedStatement statement = before(connection, sql, params);
        try {
            return statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public int update(String sql, Object...params){
        return update(getConnection(), sql, params);
    }

    public static ResultSet query(Connection connection, String sql, Object...params){
        PreparedStatement statement = before(connection, sql, params);
        try {
            return statement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public ResultSet query(String sql, Object...params){
        return query(this.getConnection(), sql, params);
    }
}
